import { useEffect } from "./useEffect";
import { ref } from "vue";

/**
 * setTimeout钩子
 * @param fn
 * @param time
 * @param options
 */
export function useTimeout(fn: () => any, time: number, options?: UseTimeoutOptions) {
  const isUnmounted = ref(false);
  let timeoutId: any = null;
  const isLoop = options?.loop ?? false;
  const isImmediate = options?.immediate ?? false;

  useEffect(() => {
    const callback = () => {
      const ret = fn();
      if (ret instanceof Promise) {
        ret.finally(() => {
          if (!isUnmounted.value && isLoop) {
            timeoutId = setTimeout(callback, time);
          }
        });
      } else if (!isUnmounted.value && isLoop) {
        timeoutId = setTimeout(callback, time);
      }
    };

    if (isImmediate) {
      fn();
    }
    timeoutId = setTimeout(callback, time);

    return () => {
      isUnmounted.value = true;
      clearTimeout(timeoutId);
    };
  });
}

export interface UseTimeoutOptions {
  loop?: boolean;
  immediate?: boolean;
}
